package com.jar.exercise.算法.数组查找;

/**
 * @author ZhangShengHao
 * @className Demo1
 * @description TODO
 * @date 2020/1/29 22:24
 */
public class Demo {
	public static void main(String[] args) {
		//String[] arr = new String[]{"张三", "里斯", "王五", "赵六", "麻子"};
		//xianFind(arr, "王五1");
		int[] arr1 = new int[]{-45, 0, 5, 12, 12, 32, 32, 56, 89};
		twoFind(arr1, 52);
	}

	/**
	 * 线性查找
	 */
	private static void xianFind(String[] arr, String index) {
		boolean flag = true;
		for (int i = 0; i < arr.length; i++) {
			if (index.equals(arr[i])) {
				System.out.println("线性查找结束，位置：" + i);
				flag = false;
				break;
			}
		}
		if (flag) {
			System.out.println("线性查找结束,没有查找到");
		}

	}

	/**
	 * 二分法查找,前提是有序
	 */
	private static void twoFind(int[] arr, int index) {
		int begin = 0;
		int end = arr.length - 1;
		boolean flag = true;
		while (begin <= end) {
			int middle = (begin + end) / 2;
			if (arr[middle] == index) {
				flag = false;
				System.out.println("找到了+++" + middle);
				break;
			}
			if (arr[middle] > index) {
				end = middle - 1;
			} else {
				begin = middle + 1;
			}

		}
		if (flag) {
			System.out.println("没有找到");
		}
	}
}
